/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim </a>, 2004
 */
package hk.com.carfield.util;

import hk.com.carfield.content.Content;
import hk.com.carfield.content.Editable;
import hk.com.carfield.core.Config;
import hk.com.carfield.core.ContentManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class ConvertLocalEncodingToUtf8 {
	// TODO testcase??
	private static void convert(final File file) throws FileNotFoundException,
			IOException {
		if (!file.exists()) {
			return;
		}
		final Charset guessedCharset = ConvertLocalEncodingToUtf8
				.guessCharsetNeedConvert(file);
		if (guessedCharset != null) {
			ConvertLocalEncodingToUtf8.convertFile(file);
		}
	}

	public static void convertFile(final File file)
			throws FileNotFoundException, IOException {
		final FileInputStream is = new FileInputStream(file);
		final String legacyEncoding = System.getProperty("file.encoding");
		final String content = IOUtils.toString(is, legacyEncoding);
		final String oldFileName = file.getAbsolutePath();
		file.renameTo(new File(file.getParentFile(), "." + file.getName() + "."
				+ legacyEncoding));
		FileUtils.writeStringToFile(new File(oldFileName), content, "UTF-8");
	}

	public static Charset guessCharsetNeedConvert(final File file)
			throws FileNotFoundException, IOException {
		// Was using api from com.glaforge.i18n package, but doesn't need this
		// function for a long time
		return null;
	}

	public static void main(final String[] args) throws IOException {
		System.out.println(System.getProperty("file.encoding"));
		final String defaultPath = System.getProperty("user.dir");
		final File file = new File(new File(defaultPath), "WEB-INF/data");
		final Config c = Config.getConfig(new File(file, "conf"));
		ConvertLocalEncodingToUtf8.process(c, c.getRoot());
	}

	private static void process(final Config c, final File file)
			throws IOException {
		if (file.isDirectory()) {
			final File[] childs = file.listFiles(c.displayFilter());
			if (childs != null) {
				for (int i = 0; i < childs.length; i++) {
					ConvertLocalEncodingToUtf8.process(c, childs[i]);
				}
			}
			ConvertLocalEncodingToUtf8
					.convert(new File(file, c.headerFileName));
			ConvertLocalEncodingToUtf8
					.convert(new File(file, c.readmeFileName));
		} else {
			final Class<? extends Content> clazz = ContentManager.getType(file);
			if (clazz != null && Editable.class.isAssignableFrom(clazz)) {
				ConvertLocalEncodingToUtf8.convert(file);
			}
		}
	}

}
